package ecomm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import ecomm.entity.User;
import ecomm.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 1. 用户列表
    @GetMapping("/list")
    public List<User> list() {
        return userService.list();
    }

    // 2. 分页用户列表
    @GetMapping("/page")
    public IPage<User> page(@RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = "10") Integer pageSize) {
return userService.pageUsers(pageNum, pageSize);
    }

    // 3. 根据 ID 获取用户详情
    @GetMapping("/{id}")
    public ResponseEntity<User> getById(@PathVariable Long id) {
        User user = userService.getById(id);
        return user != null ? ResponseEntity.ok(user) : ResponseEntity.notFound().build();
    }

    // 4. 新增用户
    @PostMapping
    public User create(@RequestBody User user) {
        userService.save(user);
        return user;
    }

    // 5. 删除用户
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        return userService.removeById(id) ? ResponseEntity.noContent().build()
                : ResponseEntity.notFound().build();
    }

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            boolean result = userService.register(user);
            if (result) {
                return ResponseEntity.ok("注册成功");
            } else {
                return ResponseEntity.ok("注册失败");
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody String username
    , @RequestBody String password) {
        try {
            String token = userService.login(username, password);
            Map<String, String> result = new HashMap<>();

            result.put("token", token);
            result.put("message", "登录成功");
            return ResponseEntity.ok(result);

        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }

        }

    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token){
        //（可选）添加日志，帮助调试
        Logger logger = LoggerFactory.getLogger(UserController.class);
        logger.info("当前用户信息：{}", userService.getUserByToken(token));
        try {
            String clean = token.replace("Bearer ", "");
            logger.info("当前用户信息：{}", userService.getUserByToken(clean));

            User user = userService.getUserByToken(clean);
            if(user != null){
                user.setPassword(null); // 屏蔽敏感数据Password
                return ResponseEntity.ok(user);
            } else {
                logger.warn("没有找到用户Token");
                return ResponseEntity.status(401).body("没有找到用户Token，或Token已过期!");
            }
        }catch (Exception e){
            logger.error("请求错误：", e);
            return ResponseEntity.status(400).body("请求错误" + e.getMessage());
        }
    }

        // 退出登录
        @PostMapping("/logout")
        public ResponseEntity<?> logout(@RequestHeader("Authorization") String token) {
            try {
                boolean result = userService.logout(token.replace("Bearer ", ""));
                return result ? ResponseEntity.ok("注销成功") : ResponseEntity.ok("注销失败");
            } catch (IllegalArgumentException e) {
                return ResponseEntity.badRequest().body(e.getMessage());
            }
        }
    }
